<template>
	<div class="app-container">
		<div ref="box3" class="flex-center">
			<total-box :total-data="totalData"></total-box>
		</div>
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-radio-group
						v-model="searchParams.productState"
						class="item-gap"
						size="small"
						@change="onStateChange"
					>
						<el-radio-button v-for="item in saleOrderStateList" :key="item.id" :label="item.id">
							<div class="margin-right-10" style="padding-bottom: 2px;">{{ item.name }}</div>
						</el-radio-button>
					</el-radio-group>
				</div>
				<div class="flex-end-center-wrap">
					<div class="flex-end-center-wrap">
						<el-checkbox v-model="quickSearch">快捷筛选</el-checkbox>
						<el-radio-group v-if="quickSearch" v-model="searchParams.period" size="small" @change="onSearchBtn">
							<el-radio-button label="-1">昨天</el-radio-button>
							<el-radio-button label="1">本天</el-radio-button>
							<el-radio-button label="2">本周</el-radio-button>
							<el-radio-button label="3">本月</el-radio-button>
							<el-radio-button label="4">本年</el-radio-button>
						</el-radio-group>
						<jk-date-picker
							v-else
							v-model="searchParams.belongDate"
							:clearable="false"
							class="search-bar-item-size2 margin-5-0 item-gap"
							placeholder="日期"
							size="small"
							style="width: 280px;"
							type="daterange"
						></jk-date-picker>
						<jk-search-input
							v-model="searchParams.customerNameOrCode"
							class="search-bar-item-size3 margin-5-0 item-gap"
							clearable
							placeholder="客户名称"
							size="small"
							@on-enter="onSearchBtn"
						></jk-search-input>
						<jk-search-input
							v-model="searchParams.saleOrderCode"
							class="search-bar-item-size3 margin-5-0 item-gap"
							clearable
							placeholder="销售订单号"
							size="small"
							@on-enter="onSearchBtn"
						></jk-search-input>
						<jk-search-input
							v-model="searchParams.productNameOrCode"
							class="search-bar-item-size3 margin-5-0 item-gap"
							clearable
							placeholder="品种"
							size="small"
							@on-enter="onSearchBtn"
						></jk-search-input>
						<jk-search-input
							v-model="searchParams.batchCode"
							class="search-bar-item-size3 margin-5-0 item-gap"
							clearable
							placeholder="批号"
							size="small"
							@on-enter="onSearchBtn"
						></jk-search-input>
						<jk-search-button @click="onSearchBtn"></jk-search-button>
					</div>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="jkTable" :data="tableData" :height="tableHeight + 20" :loading="tableLoading" border>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:align="item.align"
					:field="item.keyName"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:sortable="item.sortable"
					:title="item.title"
					:width="item.width"
				>
					<template slot-scope="scope">
						<div
							v-if="item.keyName === 'inputQty'"
							style="color: #2d8cf0;cursor: pointer;"
							@click="onSeeInputWarehouseDetailBtn(scope.row)"
						>{{ scope.row.inputQty }}</div>
						<div
							v-else-if="item.keyName === 'surplusQty'"
						>{{ calSurplus(scope.row) }}</div>
						<div
							v-else-if="item.keyName === 'outputQty'"
							style="color: #2d8cf0;cursor: pointer;"
							@click="onSeeOutputWarehouseDetailBtn(scope.row)"
						>{{ scope.row.outputQty }}</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-size="searchParams.pageSize"
					:page-sizes="searchParams.pageSizes"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<input-warehouse-detail-dialog
			:data-item="dataItem"
			:dialog-state="inputWarehouseDetailDialogState"
			:belong-date="belongDate"
			@on-visible-change="onVisibleChangeOfInputWarehouseDetailDialog"
		></input-warehouse-detail-dialog>
		<output-warehouse-detail-dialog
			:data-item="dataItem"
			:belong-date="belongDate"
			:dialog-state="outputWarehouseDetailDialogState"
			@on-visible-change="onVisibleChangeOfOutputWarehouseDetailDialog"
		></output-warehouse-detail-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, pageConfig } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import {
        productionSaleOrderInventoryCount,
        productionSaleOrderTracking
    } from '../../../api/production/productionMonitor';
    import inputWarehouseDetailDialog from './inputWarehouseDetailDialog';
    import outputWarehouseDetailDialog from './outputWarehouseDetailDialog';
    import totalBox from './components/total-box';
    import { mathJsSub } from '@/utils/jk/jk-cals';

    export default {
        name: 'SalesOrderTracking',
        components: {
            totalBox,
            outputWarehouseDetailDialog,
            inputWarehouseDetailDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                saleOrderStateList: [
                    { id: 1, states: [0, 1, 2], name: '未完成' },
                    { id: 2, states: [3], name: '已完成' }
                ],
                apiItem: {
                    'page': productionSaleOrderTracking
                },
                totalData: {},
                dataItem: {},
                quickSearch: true,
                inputWarehouseDetailDialogState: false,
                outputWarehouseDetailDialogState: false,
                dataId: null,
                tableLoading: true,
                tableData: [],
                belongDate: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    productState: 1,
                    productName: '',
                    batchCode: '',
                    customerNameOrCode: '',
                    productNameOrCode: '',
                    saleOrderCode: '',
                    belongDate: [],
                    period: 3,
                    radioTime: []
                }
            };
        },
        mounted() {
            this.getDependentData();
        },

        watch: {

            quickSearch: {
                handler: function(newVal, oldVal) {
                    if (this.quickSearch) {
                        this.searchParams.period = this.searchParams.period ? this.searchParams.period : 3;
                        this.getDependentData();
                        // this.searchParams.belongDate = [formatDate(Date.now()), formatDate(Date.now())];
                    } else {
                        // 默认是本天的时间
                        if (this.searchParams.belongDate.length === 0) {
                            this.searchParams.belongDate = [formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), formatDate(Date.now())];
                        }
                    }
                },
                deep: true
            }

        },
        methods: {
            calSurplus(row) {
                return mathJsSub(row.productQty || 0, row.inputQty || 0);
            },
            onStateChange() {
                this.tableData = [];
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
                this.getTotalDataRequest();
            },
            onSeeInputWarehouseDetailBtn(row) {
                this.dataItem = row;
                this.inputWarehouseDetailDialogState = true;
            },
            onSeeOutputWarehouseDetailBtn(row) {
                this.dataItem = row;
                this.outputWarehouseDetailDialogState = true;
            },
            onVisibleChangeOfInputWarehouseDetailDialog(e) {
                this.inputWarehouseDetailDialogState = e;
            },
            onVisibleChangeOfOutputWarehouseDetailDialog(e) {
                this.outputWarehouseDetailDialogState = e;
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },

            async getDependentData() {
                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                await this.getTotalDataRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            getPeriodRange(period, now) {
                if (period === -1) {
                    // 昨天
                    const yesterday = formatDate(Date.now() - 24 * 60 * 60 * 1000);
                    return [yesterday, yesterday];
                } else if (period === 1) {
                    // 本天
                    return [formatDate(now), formatDate(now)];
                } else if (period === 2) {
                    // 本周
                    const startOfWeek = new Date(now);
                    startOfWeek.setDate(now.getDate() - now.getDay() + 1);
                    return [formatDate(startOfWeek), formatDate(now)];
                } else if (period === 3) {
                    // 本月
                    const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
                    return [formatDate(startOfMonth), formatDate(now)];
                } else if (period === 4) {
                    // 本年
                    const startOfYear = new Date(now.getFullYear(), 0, 1);
                    return [formatDate(startOfYear), formatDate(now)];
                }
                return [null, null];
            },

            getTotalDataRequest() {
                const params = { ...this.searchParams };
                const now = new Date();
                params.period = Number(params.period);
                if (this.quickSearch) {
                    params.radioTime = this.getPeriodRange(params.period, now);
                    params.belongDate = params.radioTime;
                    delete params.radioTime;
                }
                params.serviceStateList = params.productState === 1 ? [0, 1, 2] : [3];
                params.startDate = params.belongDate[0];
                params.endDate = params.belongDate[1];
                delete params.belongDate;

                return productionSaleOrderInventoryCount(params).then(res => {
                    if (res.data.status === 200) {
                        this.totalData = res.data.res || {};
                    }
                });
            },

            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = { ...this.searchParams };
                const now = new Date();
                params.period = Number(params.period);

                if (this.quickSearch) {
                    params.radioTime = this.getPeriodRange(params.period, now);
                    params.belongDate = params.radioTime;
                    delete params.radioTime;
                }
                params.serviceStateList = params.productState === 1 ? [0, 1, 2] : [3];
                this.belongDate = params.belongDate;

                params.startDate = params.belongDate[0];
                params.endDate = params.belongDate[1];

                delete params.belongDate;
                delete params.period;
                delete params.productState;
                this.tableData = [];

                return this.apiItem['page'](params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.calTableHeight();
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                }).catch(error => {
                    this.tableLoading = false;
                    console.error('Error fetching data:', error);
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
                this.getTotalDataRequest();
            }
        }
    };
</script>
<style scoped>
.el-checkbox {
    margin-right: 5px;
}

.el-radio-group {
    margin: 5px;
}

</style>
